package com.dream.web.aop.aspectj;

import com.dream.common.exception.RespErrorException;
import com.dream.dto.DataResponse;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class CommonResponseAspect {

    private static final Logger LOG = LoggerFactory.getLogger(CommonResponseAspect.class);

    /**
     * @description: 切入点
     */
    @Pointcut("@annotation(com.dream.web.aop.annotation.CommonResponse)")
    public void point() {}




    /**
     * @功能描述:包装公共响应
     * @时间:2019年1月25日
     * @创建人:dbq
     * @param joinPoint
     * @return Object
     */
    @Around("point()")
    private Object wrapCommonResponse(ProceedingJoinPoint joinPoint){
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();

        if (method.getReturnType().equals(void.class)) {
            return null;
        }
        DataResponse<Object> result = new DataResponse<>();
        Object value;
        try {
            value = joinPoint.proceed();
            result.setCode(DataResponse.SUCCESS);
            result.setData(value);
        } catch (RespErrorException e){
            e.printStackTrace();
            result.setCode(e.getCode() == null ? -1 : e.getCode());
            result.setMessage(e.getMessage());
            LOG.error(e.getMessage());
        }catch (Throwable e) {
            e.printStackTrace();
            result.setCode(DataResponse.FAIL);
            result.setMessage(e.toString());
            LOG.error(e.getMessage());
        }
        return result;
    }
}
